package admin

import (
	"laohuo/dao"
	"laohuo/model"
	"net/http"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
)

type Wares struct{}

func (w *Wares) List(ctx *gin.Context) {
	params := struct {
		Page     uint
		Pagesize uint
	}{}
	if err := ctx.ShouldBindQuery(&params); err != nil {
		ctx.String(http.StatusBadRequest, err.Error())
		return
	}
	if params.Page == 0 {
		params.Page = 1
	}
	if params.Pagesize == 0 || params.Pagesize > 100 {
		params.Pagesize = 20
	}

	ws, err := dao.FetchWares(params.Page, params.Pagesize)
	if err != nil {
		ctx.String(http.StatusInternalServerError, err.Error())
		return
	}

	total, _ := dao.CountWares()
	ctx.JSON(http.StatusOK, struct {
		Total int
		Data  []*model.Ware
	}{total, ws})
}

func (w *Wares) Del(ctx *gin.Context) {
	id, err := strconv.Atoi(ctx.Query("id"))
	if err != nil {
		ctx.String(http.StatusBadRequest, err.Error())
		return
	}
	if id == 0 {
		ctx.String(http.StatusBadRequest, "参数错误")
		return
	}

	if err := dao.DelWares(uint(id)); err != nil {
		ctx.String(http.StatusInternalServerError, err.Error())
	}
	ctx.String(http.StatusOK, "OK")
}

func (w *Wares) Add(ctx *gin.Context) {
	params := struct {
		Name string
		Desc string
	}{}
	if err := ctx.ShouldBindJSON(&params); err != nil {
		ctx.String(http.StatusBadRequest, err.Error())
		return
	}
	if len(params.Name) == 0 {
		ctx.String(http.StatusBadRequest, "参数错误")
		return
	}

	ware := &model.Ware{
		Name: params.Name,
		Desc: params.Desc,
		Time: uint(time.Now().Unix()),
	}
	if err := dao.AddWares(ware); err != nil {
		ctx.String(http.StatusInternalServerError, err.Error())
	}
	ctx.JSON(http.StatusOK, ware)
}
